import { defineStore } from 'pinia';
import { loginFun, userinfoFun } from '~/N/api/app';
import { local_storage } from '@/utils/storage';

export const TOKEN = 'Pro-Auth-Token';
export const USER_INFO = 'Pro-User-Info';

const useMainApp = defineStore('app', {
  persist: true,
  state: () => {
    return {
      [TOKEN]: localStorage.getItem(TOKEN),
      [USER_INFO]: local_storage.get(USER_INFO)
    };
  },
  getters: {
    token: state => state[TOKEN] || null,
    userinfo: state => state[USER_INFO] || {}
  },
  actions: {
    CLEAR_TOKEN() {
      localStorage.clear();
      sessionStorage.clear();
    },
    LOGIN(data) {
      if (!data) return;
      return new Promise((resolve, reject) => {
        loginFun(data)
          .then(res => {
            const data = res.data.data;
            localStorage.setItem(TOKEN, data.token);
            this.$state[TOKEN] ??= data.token;
            // this.USERINFO();
            resolve(res);
          })
          .catch(error => reject(error));
      });
    },
    USERINFO() {
      return new Promise((resolve, reject) => {
        userinfoFun()
          .then(res => {
            const { data: { data } } = res;
            console.log(data, '>>>用户信息');
            local_storage.set(USER_INFO, data);
            this.$patch(state => state[USER_INFO] = data);
            resolve(res);
          })
          .catch(error => reject(error));
      });
    }
  }
});

export default useMainApp;
